/*****
 *现在文件，uniapp不能保存文件到，windows,只能通过调用 web.blink(chorme核)
 ****/
import Vue from 'vue'
import config from "../conf/Config.js";

import cmd from "../Cmd.js";

import lang from "../conf/Lang.js";

import staticConst from "../const/StaticConst.js"

var downloadFile = {
	cookies: "",
};

/**下载产品模板**/
downloadFile.downGdsTlp = function (type) {
	let obj = {};
	if (type == 1) {
		obj.responseURL = config.host + config.GOODS_EXPORT_EXAMPLE_ADD;
	} else {
		obj.responseURL = config.host + config.GOODS_EXPORT_EXAMPLE_ALL;
	}
	obj.referer = String(window.location.href).split("#")[0];
	obj.host = config.host;
	obj.saveTitle = lang.gdsUpAndDownTxt.gdsSaveTitle;
	obj.downTilte = lang.gdsUpAndDownTxt.gdsDownTilte;

	let t = new Date().getTime();
	obj.fileName = lang.gdsUpAndDownTxt.gdsTlpFileNameTxt + t + lang.gdsUpAndDownTxt.gdxTlpFileSuffixTxt;
	console.log('下载产品模板');
	window.open(obj.responseURL);
	// cmd.external(cmd.CMD_SAVE_FILE,obj);
}

/**导出产品列表
 *goodsinfo/goods_export?seach_onshale=&seach_catid=&seach_tag=&seach_btn_title=&seach_btn_item_no=&seach_btn_code=&export_type=2 HTTP/1.1
 ***/
downloadFile.exportGdsList = function () {
	let obj = {};
	obj.responseURL = config.host + config.GOODS_EXPORT_TYPE
	obj.referer = String(window.location.href).split("#")[0];
	obj.host = config.host;
	obj.saveTitle = lang.gdsUpAndDownTxt.gdsExportTitle;
	obj.downTilte = lang.gdsUpAndDownTxt.gdsExportWinTit;
	let t = new Date().getTime();
	obj.fileName = lang.gdsUpAndDownTxt.gdsExpFileName + t + lang.gdsUpAndDownTxt.gdxTlpFileSuffixTxt;
	console.log('导出产品');
	window.open(obj.responseURL);
	// cmd.external(cmd.CMD_SAVE_FILE, obj);

}

/*****网页导出产品列表*****/
downloadFile.webExportGdsList = function () {
	let url = String(config.host).replace('index.php?/', '') + config.GOODS_EXPORT_TYPE;
	let t = new Date().getTime();
	let fn = lang.gdsUpAndDownTxt.gdsExpFileName + t + lang.gdsUpAndDownTxt.gdxTlpFileSuffixTxt;
	this.webDowonloadTlp(url, fn);
}

/*****上传文件*******/
downloadFile.uploadAPI = function (param, url, back) {
	uni.showLoading({
		title: lang.uploadingTxt
	})
	let that = this;
	let fData = new FormData();
	param.token = this.cookies;
	param.app = staticConst.CLIENT_TYPE
	for (let k in param) {
		fData.append(k, param[k]);
	}
	let xhr = new XMLHttpRequest();
	let surl = url; //config.host + config.GOODS_IMPORT_SAVE;//util.commonUrl() + api.uploadUrl;
	xhr.open("POST", surl, true);
	xhr.setRequestHeader('sessionid', uni.getStorageSync('sessionid'));
	xhr.onload = function (e) {
		console.log({
			title: "上传文件完成！"
		});
	};

	xhr.onreadystatechange = () => {
		uni.hideLoading();
		if (xhr.readyState == 4 && xhr.status == 200) {
			try {
				let res = JSON.parse(xhr.responseText);
				if (res && back)
					back.apply(null, [res]);
			} catch (e) {
				console.log(e)
			}
		}
	}
	xhr.setRequestHeader('enctype', "multipart/form-data");
	xhr.send(fData);
}

/*****现在产品模板文件******/
downloadFile.downloadCustomTlp = function () {
	let obj = {};
	obj.responseURL = config.host + config.CUSTOMER_IMPORT;
	obj.referer = String(window.location.href).split("#")[0];
	obj.host = config.host;
	obj.saveTitle = lang.gdsUpAndDownTxt.gdsSaveTitle;
	obj.downTilte = lang.gdsUpAndDownTxt.gdsDownTilte;

	let t = new Date().getTime();
	obj.fileName = lang.customerTxt.customTlpTxt + t + lang.gdsUpAndDownTxt.gdxTlpFileSuffixTxt;
	console.log('下载客户模板');
	window.open(obj.responseURL);
	// cmd.external(cmd.CMD_SAVE_FILE, obj);
}

/*****门店销售记录导出******/
downloadFile.downloadShopSellExport = function (p) {
	let obj = {};
	// let p = {"is_yy":"2","page":0,"pfrom":"0","pnum":"20","shopid":"","stime":"2025-04-21","time":"1","uid_cp":""};
	let queryString = Object.keys(p).map(key => `${key}=${p[key]}`).join('&');
	const token = uni.getStorageSync('token')
	obj.responseURL = config.host + `report/shop_sell_export?token=${token}&${queryString}`;
	obj.referer = String(window.location.href).split("#")[0];
	obj.host = config.host;
	obj.saveTitle = lang.gdsUpAndDownTxt.gdsSaveTitle;
	obj.downTilte = lang.gdsUpAndDownTxt.gdsDownTilte;
	let t = new Date().getTime();
	obj.fileName = lang.customerTxt.customTlpTxt + t + lang.gdsUpAndDownTxt.gdxTlpFileSuffixTxt;
	try {
		
		Vue.prototype.$confirm('请到浏览器【下载记录/下载记录】检查下载的文件', '提示', {
			confirmButtonText: '确定',
			type: 'info',
			center: true,
			showClose: false,
		}).then(() => {
			window.open(obj.responseURL, '_blank');
		}).catch(() => { })

		// alert('请到浏览器【下载记录/下载记录】检查下载的文件')
		// Vue.prototype.$message.success('请到浏览器【下载记录/下载记录】检查下载的文件')
		// setTimeout(() => {
		// 	window.open(obj.responseURL, '_blank');
		// }, 3000)
		
	} catch (error) {
		alert('下载失败，请联系管理员')
	}
	// cmd.external(cmd.CMD_SAVE_FILE, obj);
}

/*****下载模板********/
downloadFile.webDowonloadTlp = function (url, fName) {
	let that = this;
	const fileName = fName;
	var url2 = url.replace(/\\/g, '/');
	var xhr = new XMLHttpRequest();
	xhr.open('GET', url2, true);
	xhr.responseType = 'blob';
	xhr.setRequestHeader('sessionid', uni.getStorageSync('sessionid'));
	// 为了避免大文件影响用户体验，建议加loading
	xhr.onload = function () {
		uni.showLoading({
			title: '加载中',
		});
		if (xhr.status === 200) {
			uni.hideLoading();
			// 获取文件blob数据并保存
			downloadFile.saveAs(xhr.response, fileName);
		} else {
			uni.hideLoading();
			uni.showToast({
				title: "下载文件失败",
				icon: "none",
				duration: 2000
			})
		}
	};
	xhr.send();
}

/*****保存文件*******/
downloadFile.saveAs = function (blob, filename) {
	if (window.navigator.msSaveOrOpenBlob) {
		navigator.msSaveBlob(blob, filename);
	} else {
		const link = document.createElement('a');
		const body = document.querySelector('body');
		let binaryData = [];
		binaryData.push(blob);
		link.href = window.URL.createObjectURL(new Blob(binaryData));
		link.download = filename;
		// fix Firefox
		link.style.display = 'none';
		body.appendChild(link);
		link.click();
		body.removeChild(link);
		window.URL.revokeObjectURL(link.href);
	}
}

downloadFile.webDowonloadTlpNew = function () {
	//只能是GET请求
	// 　　url: base.baseUrl + `/electricStation/exportData?siteId=1&startTime=${e[0]}&endTime=${e[1]}`, //请求地址
	// 　　header: {
	// 　　　　Authorization: 'Bearer ' + uni.getStorageSync('SET_TOKEN') //请求头。
	// 　　},
	// 　　success: res => {
	// 　　//下载成功
	// 　　if (res.statusCode === 200) {
	// 　　　　var sFilePath = res.tempFilePath;
	// 　　　　//保存文件
	// 　　　　uni.saveFile({
	// 　　　　　　tempFilePath: res.tempFilePath, //下载成功之后返回的临时路径
	// 　　　　　　success: e => {
	// 　　　　　　　　console.log(e);
	// 　　　　　　　　var savedFilePath = e.savedFilePath;

	// 　　　　　　　　//解决下载返回文件名和保存文件名不一致问题
	// 　　　　　　　　this.fSetFileName(e.savedFilePath, sFilePath);
	// 　　　　　　},
	// 　　　　　　fail: e => {
	// 　　　　　　　　uni.showToast({
	// 　　　　　　　　　　title: `保存失败` + e
	// 　　　　　　　　});
	// 　　　　　　}
	// 　　　　　});
	// 　　　　}
	// 　　},
	// 　　fail: e => {
	// 　　　　uni.showToast({
	// 　　　　　　title: `文件下载失败` + e,
	// 　　　　　　icon: 'none'
	// 　　　　});
	// 　　}
}


downloadFile.fSetFileName = function (sFilePath, sFileName) {
	var sFileName = sFileName.split('/')[sFileName.split('/').length - 1]; //原来的文件名
	var aFileUrl = sFilePath.split('/').splice(0, sFilePath.split('/').length - 1); //saveFile API保存的本地地址
	var url = base.baseUrl + `/electricStation/exportData?siteId=1&startTime=${this.range[0]}&endTime=${this.range[1]}`; //请求地址
	let dtask = plus.downloader.createDownload(
		url, {
		filename: 'file://' + aFileUrl.join('/') + '/' + sFileName //利用保存路径，实现文件的重命名
	},
		(d, status) => {
			if (status == 200) {
				let fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename);
				this.fGetSavedFileList();

				uni.openDocument({
					filePath: fileSaveUrl,
					fail: e => {
						uni.showToast({
							title: `打开失败` + e
						});
					}
				});
			} else {
				//下载失败
				plus.downloader.clear(); //清除下载任务
			}
		}
	);
	dtask.setRequestHeader('Authorization', 'Bearer ' + uni.getStorageSync('SET_TOKEN'));
	dtask.start();
}



export default downloadFile;